#! /bin/python env
import pygtk
import unittest
import socket
import re
import gobject
BUFF_SIZE = 4096

class mlcommander:
    def __init__(self):
        self.is_connected = False;
        self.connect_to = 5000
        self.ml_host = '127.0.0.1'
        self.ml_port = 4000
        self.s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        #self.s.settimeout(self.connect_to)
        gobject.timeout_add(self.connect_to, self.connect2server)
        self.connect2server()
        pass

    def __del__(self):
        print 'Bye'
        self.execute('q')
        self.s.close()

    def execute(self, cmd):
        str = ''
        if self.is_connected:
            if self.s.send(cmd + '\n') > 0:
	            str = self.s.recv(BUFF_SIZE)
        return str

    def connect2server(self):
        print 'Connect to mlnet server...',
        try:
            self.s.connect((self.ml_host, self.ml_port))
        except socket.error,e:
            print 'Error, %s' % str(e)
        else:
            self.is_connected = True
            self.s.recv(BUFF_SIZE)
            print 'OK'
        # return True to continue next timer
        return not self.is_connected


if __name__ == '__main__':
    mlc = mlcommander()
    while mlc.is_connected != True: 
    	from time import sleep
    	sleep(1)
    ret = mlc.execute(raw_input('cmd >'))
    print ret 

